import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
// 引入antd的样式
import {
  Button,
  Form,
  Input,
  Select,
  Table,
  Card,
  Col,
  Row,
  message,
} from "antd";
// api请求
import {
  getHospitalListRequest,
  ProvinceTypeRequest,
  CityTypeRequest,
  ChangeStatusRequest,
} from "@/api/hospital/hospitalList";
import type {
  getHosListSearchParamsType,
  hospitalListContentType,
  hospitalListItemsType,
  ProvinceReturnAryType,
} from "@/api/hospital/model/hospitalListTypes";
export default function HospitalList() {
  const navigate = useNavigate();
  //通过Form组件上的一个useForm方法,可以创建实例,然后在某一个Form组件上添加一个form属性,值为当前实例,那么Form表单和当前的form实例就关联起来了
  const [form] = Form.useForm();
  //定义isLoading(table是否加载中)
  const [isLoading, setIsLoading] = useState(false);
  //控制当前页码的状态
  const [page, setPage] = useState(1);
  //控制每页显示的条数
  const [limit, setLimit] = useState(3);
  //控制查询时用户输入的表单参数
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>(
    {}
  );
  // 控制渲染表单渲染的数据
  const [tableData, setTableDate] = useState<hospitalListContentType>([]);
  //控制总数据的数量
  const [total, setTotal] = useState(0);
  // 存储所有省份信息的数据
  const [province, setProvince] = useState<ProvinceReturnAryType>([]);
  // 存储所有所有市级的数据
  const [cityList, setCityList] = useState<ProvinceReturnAryType>([]);
  // 存储所有得区级得数据
  const [area, setArea] = useState<ProvinceReturnAryType>([]);
  // 控制医院类型
  const [HospitalType, setHospitalType] = useState<ProvinceReturnAryType>([]);
  //控制重新渲染的state
  const [reRender, setReRender] = useState(true);
  // 初始化的时候,发送医院列表的请求
  useEffect(() => {
    setIsLoading(true);
    const getHospitalList = async () => {
      const res = await getHospitalListRequest(page, limit, searchParams);
      // 修改表单的数据
      setIsLoading(false);
      setTableDate(res.content);
      // 修改总页数
      setTotal(res.totalElements);
    };
    getHospitalList();
  }, [page, limit, searchParams, reRender]);
  // 初始化的时候获取所有省份的数据
  useEffect(() => {
    const pr = async () => {
      const re = await ProvinceTypeRequest();
      setProvince(re);
    };
    pr();
  }, []);
  // 初始化的时候立即请求医院类型
  useEffect(() => {
    const re = async () => {
      const res = await CityTypeRequest("10000");
      setHospitalType(res);
    };
    re();
  }, []);
  // 事件回调函数
  // 省份发生改变时 获取对应得到市级数据
  const getCityList = async (value: string) => {
    const re = await CityTypeRequest(value);
    setCityList(re);
    // 切换省时 市级和区级得数据不显示
    form.setFieldsValue({ cityCode: null, districtCode: null });
    // 清空区级得数据
    setArea([]);
  };
  //市级发生变化时 获取对象得到区级数据
  const getAreaList = async (value: string) => {
    const re = await CityTypeRequest(value);
    setArea(re);
    // 切换市级时 区级得数据不显示
    form.setFieldsValue({ districtCode: null });
  };
  //3.查询表单的提交事件
  const districtCode = (value: getHosListSearchParamsType) => {
    // 修改用户查询时的数据 并重新渲染
    setSearchParams(value);
    // 搜索时自动跳到第一页
    setPage(1);
  };
  // 4.清空时
  const clearDate = () => {
    setSearchParams({});
    // 搜索时自动跳到第一页
    setPage(1);
  };
  // 5.点击上下线 更改状态
  const ChangeStatus = (id: string, status: 0 | 1) => {
    return async () => {
      await ChangeStatusRequest(id, status);
      message.success(status ? "上线成功" : "下线成功");
      setReRender(!reRender);
    };
  };
  //6.点击排班规则
  const showScheduleHandle = (hoscode: string) => {
    return () => {
      navigate(`/syt/hospital/hospitalSchedule/${hoscode}`);
    };
  };

  const columns = [
    {
      title: "序号",
      width: 60,
      dataIndex: "index",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      render(logoData: string) {
        return <img width={120} src={`data:image/jpeg;base64,${logoData}`} />;
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "signKey",
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress;
      },
    },
    {
      title: "状态",
      render(_: any, data: hospitalListItemsType) {
        return data.status === 0 ? "下线" : "上线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      render(_: any, data: hospitalListItemsType) {
        return (
          <div>
            {/* 点击查看时 页面跳转 */}
            <Button
              type="primary"
              onClick={() => {
                navigate(`/syt/hospital/hospitalShow/${data.id}`);
              }}
            >
              查看
            </Button>

            <Button type="primary" onClick={showScheduleHandle(data.hoscode)}>
              排班
            </Button>
            <Button
              type="primary"
              onClick={ChangeStatus(data.id, data.status ? 0 : 1)}
            >
              {data.status ? "下线" : "上线"}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Card>
        <Form name="basic" form={form} onFinish={districtCode}>
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="provinceCode">
                <Select
                  placeholder="请选择省"
                  allowClear
                  onChange={getCityList}
                >
                  {province.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="cityCode">
                <Select
                  placeholder="请选择市"
                  allowClear
                  onChange={getAreaList}
                >
                  {cityList.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="districtCode">
                <Select placeholder="请选择区" allowClear>
                  {area.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hosname">
                <Input placeholder="医院名称" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hoscode">
                <Input placeholder="医院编号" />
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item name="hostype">
                <Select placeholder="医院类型" allowClear>
                  {HospitalType.map((item) => {
                    return (
                      <Select.Option value={item.value} key={item.id}>
                        {item.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={20}>
            <Col span={3}>
              <Form.Item name="status">
                <Select placeholder="医院状态" allowClear>
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={1}>
              <Form.Item>
                <Button type="default" htmlType="reset" onClick={clearDate}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
        <Table
          style={{ marginTop: "30px" }}
          columns={columns}
          // 接受渲染的值
          dataSource={tableData}
          scroll={{ x: 1100 }}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}
          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,
            showTotal(total) {
              return `总共有${total}条数据`;
            },
            // 点击切换页码 并渲染页面
            onChange(current: number, pageSize: number) {
              setPage(current);
              setLimit(pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
